package waysing.cream.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import waysing.cream.dao.*;
import waysing.cream.entity.*;
import waysing.cream.service.MovieSourceService;
import waysing.cream.utils.HttpUtil;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by weixin on 2018/3/8.
 */
@Service
public class MovieSourceServiceImpl implements MovieSourceService {
    @Autowired
    private MovieSourceDao movieSourceDao;
    @Autowired
    private MovieDao movieDao;
    @Autowired
    private ActorDao actorDao;
    @Autowired
    private DirectorDao directorDao;
    @Autowired
    private GenreDao genreDao;
    @Override
    @Transactional
    public Movie captureFromDouban(String name) {
        System.out.println("你搜索的电影" + name);
        //拼接搜索url
        StringBuffer searchUrl = new StringBuffer("https://api.douban.com/v2/movie/search?q=").
                      append(name).append("&start=0&count=1");
        byte[] b = HttpUtil.httpConnection(searchUrl.toString());
        String searchData = null;
        try {
            searchData = new String(b,"UTF-8");

            System.out.println("搜索到的电影信息：" + searchData);
            Map<String, Object> map = JSON.parseObject(searchData, Map.class);

            JSONArray jsonArray = (JSONArray) map.get("subjects");
            Map<String, Object> obj = (Map<String, Object>) jsonArray.get(0);
            String id = String.valueOf(obj.get("id"));
            //根据豆瓣Id 判断是否已抓过该视频
            MovieSource ms = movieSourceDao.findMovieSource(id);
            if(ms != null){
                return ms.getMovie();
            }
            StringBuilder detailUrl = new StringBuilder("https://api.douban.com/v2/movie/subject/").append(id);
            System.out.println("电影详细Url:" + detailUrl);
            String detail = new String(HttpUtil.httpConnection(detailUrl.toString()), "UTF-8");

            JSON json  = JSON.parseObject(detail);
            System.out.println("取到的电影详细信息" + json.toJSONString());
            MovieSource movieSource = new MovieSource(json.toJSONString(), name, id);
            Map<String, Object> detailMap = (Map) json;
            String summary = detailMap.get("summary") != null?detailMap.get("summary").toString():null;
            String area = detailMap.get("countries") != null?detailMap.get("countries").toString():null;
            Map<String, String> imgMap = (Map<String, String>) detailMap.get("images");
            String largeImg = imgMap.get("large");
            //上映日期
            String year = (String) detailMap.get("year");
            Date publishDate =  DateUtils.parseDateStrictly(year,"yyyy");
            List<String> genres = (List<String>) detailMap.get("genres");
            List<Map<String, Object>> actors = (List<Map<String, Object>>) detailMap.get("casts");
            List<Map<String, Object>> directors = (List<Map<String, Object>>) detailMap.get("directors");
            Movie movie = new Movie(name,publishDate, summary, movieSource, area, largeImg, new Date(), new Date());
            if(directors != null && !directors.isEmpty()){
                for (Map<String, Object> directorMap : directors){
                    String directorName = String.valueOf(directorMap.get("name"));
                    Map<String, String> avatars = (Map<String, String>) directorMap.get("avatars");
                    String large = avatars.get("large");
                    String directorDoubanId = String.valueOf(directorMap.get("id"));
                    //判断是否已存在该导演
                    Director director = directorDao.findDirector(directorDoubanId);
                    if(director == null){
                        director = new Director(directorName, large, directorDoubanId, new Date(), new Date());
                    }
                    movie.getDirectors().add(director);
                }
            }
            if(actors != null && !actors.isEmpty()){
                for(Map<String, Object> actorMap : actors){
                    String actorName = String.valueOf(actorMap.get("name"));
                    Map<String, String> avatars = (Map<String, String>) actorMap.get("avatars");
                    String large = avatars.get("large");
                    String actorDoubanId = String.valueOf(actorMap.get("id"));
                    //需要判断是否已存在该演员
                    Actor actor = actorDao.findActor(actorDoubanId);
                    if(actor == null){
                        actor = new Actor(actorName,large, actorDoubanId, new Date(), new Date());
                    }
                    movie.getActors().add(actor);
                }
            }
            for(String genreStr : genres){
                //需要判断是否已存在该流派
                Genre genre = genreDao.findGenre(genreStr);
                if (genre == null){
                    genre = new Genre(genreStr, new Date(), new Date());
                }
                movie.getGenres().add(genre);
            }
//            movieSorce.setMovie(movie);
            movieDao.save(movie);
            movieSourceDao.save(movieSource);
            return movie;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> searchByName(String name) {
        //拼接搜索url
        StringBuffer searchUrl = new StringBuffer("https://api.douban.com/v2/movie/search?q=").
                append(name).append("&start=0&count=15");
        byte[] b = HttpUtil.httpConnection(searchUrl.toString());
        String searchData = null;
        try {
            searchData = new String(b, "UTF-8");

            System.out.println("搜索到的电影信息：" + searchData);
            Map<String, Object> map = JSON.parseObject(searchData, Map.class);
            List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("subjects");
            return list;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public Page<Movie> getMovie(int count){
        Pageable pageable = new PageRequest(0,count);
        Page<Movie> page = movieDao.findAll(pageable);
        return page;
    }
}